package collectormsg

import (
	"context"
	"dash/users"
	"database/sql"
	"errors"
	"github.com/go-kit/kit/log"
	"strings"
)

type OrganizationRepository interface {
	GetAllUser(ctx context.Context, id string) ([]*users.User, error)
	GetOrganizationTree(_ context.Context) ([]*CollectorOrganization, error)
	GetCollector(_ context.Context, ids []string) ([]*Collector, error)
}

type defaultOrganizationRepository struct {
	conn   *sql.DB
	logger log.Logger
}

func NewCollectorRepository(conn *sql.DB, logger log.Logger) OrganizationRepository {
	return &defaultOrganizationRepository{
		conn:   conn,
		logger: logger,
	}
}

func (r *defaultOrganizationRepository) GetAllUser(ctx context.Context, id string) ([]*users.User, error) {
	rows, err := r.conn.Query("SELECT id,name  FROM user where organId=?", id)
	if err != nil {
		_ = r.logger.Log("get users by organizationId error:", err)
		return nil, errors.New("请重试")
	}
	defer func() {
		err = rows.Close()
		if err != nil {
			_ = r.logger.Log("get users by organizationId close error:", err)
		}
	}()
	
	userRes := make([]*users.User, 0)
	for rows.Next() {
		var user users.User
		err = rows.Scan(&user.Id, &user.Name)
		if err != nil {
			_ = r.logger.Log("get users by organizationId scan error:", err)
			continue
		}
		userRes = append(userRes, &user)
	}
	return userRes, nil
}

func (r *defaultOrganizationRepository) GetOrganizationTree(ctx context.Context) ([]*CollectorOrganization, error) {
	rows, err := r.conn.Query("SELECT id,name,parentId FROM organization")
	if err != nil {
		_ = r.logger.Log("get  organization error:", err)
		return nil, errors.New("请重试")
	}
	defer func() {
		err = rows.Close()
		if err != nil {
			_ = r.logger.Log("get organization close error:", err)
		}
	}()
	organRes := make([]*CollectorOrganization, 0)
	for rows.Next() {
		var organ CollectorOrganization
		parentId := sql.NullString{String:"", Valid:false}
		err = rows.Scan(&organ.Id, &organ.Name, &parentId)
		if parentId.Valid  {
			organ.ParentId = parentId.String
		}
		if err != nil {
			_ = r.logger.Log("get organization scan error:", err)
			continue
		}
		organRes = append(organRes, &organ)
	}
	return organRes, nil
}

func (r *defaultOrganizationRepository) GetCollector(_ context.Context, ids []string) ([]*Collector, error) {
	var sqlRow = "select DISTINCT id,name from collector inner join collector_user as cu on cu.collectorId=collector.id where"
	var args []interface{}
	for _, id := range ids {
		args = append(args, id)
	}
	query := " cu.userId in (" + "?" + strings.Repeat(",?", len(ids)-1) + ")"
	rows, err := r.conn.Query(sqlRow + query, args...)
	if err != nil {
		_ = r.logger.Log("get collector error:", err)
		return nil, errors.New("请重试")
	}
	defer func() {
		err = rows.Close()
		if err != nil {
			_ = r.logger.Log("get collector close error:", err)
		}
	}()
	collectorRes := make([]*Collector, 0)
	for rows.Next() {
		var collector Collector
		err = rows.Scan(&collector.Id, &collector.Name)
		if err != nil {
			_ = r.logger.Log("get collector scan error:", err)
			continue
		}
		collectorRes = append(collectorRes, &collector)
	}
	return collectorRes, nil
}
